<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['model:shop:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['model:shop:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['model:shop:export']"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="shopList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="封面图" align="center" prop="coverImg">
        <template slot-scope="scope">
          <img class="avatar1" :src="scope.row.coverImg" />
        </template>
      </el-table-column>
      <!--<el-table-column label="轮播图" align="center" prop="bannerImgs" />-->
      <el-table-column label="基础价格" align="center" prop="basePrice">
        <template slot-scope="scope">
          <span>{{ towNumber(scope.row.basePrice) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠价" align="center" prop="price">
        <template slot-scope="scope">
          <span>{{ towNumber(scope.row.price) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="integral">
        <template slot-scope="scope">
          <span>{{ towNumber(scope.row.integral) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="number" />
      <!--<el-table-column label="已售数量" align="center" prop="soldNumber" />-->
      <!--<el-table-column label="商品详情(富文本)" align="center" prop="shopDetails" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['model:shop:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['model:shop:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      class="form-dialog"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImg">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-progress="handleAvatarProgress"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.coverImg" :src="form.coverImg" class="avatar1" />
            <i v-else class="el-icon-plus avatar-uploader-icon1"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图" prop="fileList">
          <el-upload
            list-type="picture-card"
            :limit="imgLimit"
            :action="uploadUrl"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-change="handleChangeImg"
            :before-upload="beforeAvatarUpload"
            :class="{ hide: hideUpload }"
            :file-list="form.fileList"
          >
            <i class="el-icon-plus"></i>
            <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb，推荐尺寸700*700</div>-->
          </el-upload>
        </el-form-item>
        <el-form-item label="基础价格" prop="basePrice">
          <el-input v-model="form.basePrice" placeholder="请输入基础价格" type="number" />
        </el-form-item>
        <el-form-item label="优惠价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入优惠价" type="number" />
        </el-form-item>
        <el-form-item label="所需积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入积分" type="number" />
        </el-form-item>
        <el-form-item label="商品数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入商品数量" type="number" />
        </el-form-item>
        <el-form-item label="商品详情" prop="shopDetails">
          <editor v-model="form.shopDetails" style="height: 500px"></editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loadingForm" @click="submitForm">
          <span v-if="!loadingForm">确 认</span>
          <span v-else>提 交 中...</span>
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon1 {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar1 {
  width: 60px;
  height: 60px;
  margin: 0 auto;
  border-radius: 3px;
  display: block;
}
.form-dialog .el-dialog {
  top: 28% !important;
}
.el-form-item__content .el-dialog {
  top: 25% !important;
}
.el-upload--picture-card {
  width: 80px !important;
  height: 80px !important;
  line-height: 86px;
}
.el-upload-list__item {
  width: 80px !important;
  height: 80px !important;
}
/*隐藏上传按钮*/
.hide .el-upload--picture-card {
  display: none;
}
/*在样式把这个is-ready给隐藏掉就好了，就是这么Easy*/
.el-upload-list__item.is-ready {
  display: none !important;
}
</style>

<script>
import {
  listShop,
  getShop,
  delShop,
  addShop,
  updateShop,
  exportShop,
} from "@/api/model/shop";
import Editor from "@/components/Editor";

export default {
  name: "Shop",
  components: { Editor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表单防重复提交
      loadingForm: false,
      //上传轮播图数量
      imgLimit: 5,
      hideUpload: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      shopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        delStatus: 0,
        orderByColumn: "id",
        isAsc: "desc",
        title: undefined,
      },
      // 表单参数
      form: {},
      //上传图片
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/app/upload",
      baseUrl: process.env.VUE_APP_BASE_API,
      dialogImageUrl: "",
      dialogVisible: false,
      // 表单校验
      rules: {
        title: { required: true, message: "请输入标题", trigger: "blur" },
        basePrice: { required: true, message: "请输入产品价格", trigger: "blur" },
        price: { required: true, message: "请输入产品价格", trigger: "blur" },
        // integral:{required:true, message: '请输入积分', trigger: 'blur'},
        number: { required: true, message: "请输入产品数量", trigger: "blur" },
        coverImg: { required: true, message: "请上传封面" },
        fileList: { required: true, message: "请上传轮播图" },
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listShop(this.queryParams).then((response) => {
        this.shopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //格式化金额显示
    towNumber(val) {
      return val != null ? val.toFixed(2) : "";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        coverImg: null,
        bannerImgs: null,
        basePrice: null,
        price: null,
        number: null,
        shopDetails: null,
        createTime: null,
        updateTime: null,
        delStatus: "0",
        fileList: [],
      };
      this.resetForm("form");
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.form.coverImg = res.fileName;
      } else {
        this.msgError(res.msg);
      }
    },
    handleAvatarProgress(event, file, fileList) {
      console.log(event.total);
      console.log(file.size);
      console.log(event.percent);
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //多图上传
    //删除图片
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.imgSize;
      this.form.fileList = fileList;
    },
    //多图上传成功
    handleSuccess(res, file, fileList) {
      if (res.code === 200) {
        let img = { url: res.fileName };
        this.form.fileList.push(img);
        this.hideUpload = fileList.length >= this.imgSize;
      } else {
        this.errMsg(res.msg);
      }
    },
    //多图变动
    handleChangeImg(file, fileList) {
      this.hideUpload = fileList.length >= this.imgSize;
    },
    /*多图上传END*/

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getShop(id).then((response) => {
        this.form = response.data;
        let baseURL = this.baseUrl;
        if (response.data.bannerImgs != null && response.data.bannerImgs !== "") {
          let newPictures = response.data.bannerImgs.split(",");
          this.form.fileList = newPictures.map(function (value) {
            var obj = {};
            obj.url =  value;
            return obj;
          });
        }

        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loadingForm = true;

          let baseURL = this.baseUrl;

          if (this.form.fileList != null && this.form.fileList.length > 0) {
            let newPictures = this.form.fileList.map(function (value) {
              return value["url"].replace(baseURL, "");
            });
            this.form.bannerImgs = newPictures.join(",");
          }

          if (this.form.id != null) {
            updateShop(this.form).then((response) => {
              this.loadingForm = false;
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.reset();
                this.getList();
              }
            });
          } else {
            addShop(this.form).then((response) => {
              this.loadingForm = false;
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.reset();
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delShop(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有商品信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportShop(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
  },
};
</script>
